import axios from "axios";
import qs from 'qs';

axios.defaults.baseURL = 'https://v1.itooi.cn';//默认url
// axios.defaults.withCredentials = true; //配置允许跨域携带cookie
axios.defaults.timeout = 10000;  // 超时时间  10s
axios.defaults.headers.post['Content-Type'] = 'application/json';// 全局设定请求类型

// 添加一个响应拦截器
axios.interceptors.response.use(response => {
    return response.data     // 其他的不要了，只拿data就好
}, error => {
    console.log(error)
    return Promise.reject(error);
});


let http ={
    post:'',
    get:''
}

http.post = params => {
    const token = localStorage.getItem("token") || "";
    let $axios;
    if (params.upload) {
        params.data.append('token', token ? token : "")
        let config = {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        };
        $axios = axios.post(params.url, params.data, config)
    } else if (params.noToken) {
        let data = qs.stringify(Object.assign({}, params.data))
        $axios = axios.post(params.url, data)
    } else {
        let data = qs.stringify(Object.assign({}, params.data, token ? {
            token
        } : {}))
        $axios = axios.post(params.url, data)
    }
    return new Promise((resolve,reject) => {
        $axios.then((res) => {
            if (res.code === 0) {
                if (token) localStorage.removeItem("token");
                console.log('未登录')
            } else if (res.code === 200) {
                console.log(params.url + ':', res);
                params.success(res)
            } else if (res.code === 400) {
                params.error(res)
            } else{
                params.error(res)
            }
        })
        .catch(err => {
            console.log('服务器请求失败', err)
        })
    })
}

http.get = params => {
    const token = localStorage.getItem("token") || "";
    return new Promise((resolve,reject) => {
        axios.get(params.url , {
            params: Object.assign({}, params.data, token ? {
                token
            } : "")
        }).then((res) => {
            if (res.code === 0) {
                if (token) localStorage.removeItem("token");
                console.log('未登录')
            } else if (res.code === 200) {
                console.log(params.url + ':', res);
                params.success(res)
            } else if (res.code === 400) {
                params.error(res)
            } else{
                params.error(res)
            }
        })
        .catch(err => {
            console.log('服务器请求失败', err)
        })
    })
}

export default http